import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { Location } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { BoardRecordVo } from 'src/app/model/board-record-vo';
import { EntityPageResult } from 'src/app/model/entity-page-result';
import { MemberVo } from 'src/app/model/member-vo';
import { BoardService } from 'src/app/services/board.service';
import { BtnNaviSharedService } from 'src/app/services/btn-navi-shared.service';
import { MemberStorageService } from 'src/app/services/member-storage.service';
import { UtilService } from 'src/app/services/util.service';
import { map } from 'rxjs/operators';
import { environment } from 'src/environments/environment';
import { HttpErrorResponse } from '@angular/common/http';
@Component({
  selector: 'app-personal-favorite-board-result',
  templateUrl: './personal-favorite-board-result.component.html',
  styles: [``]
})
export class PersonalFavoriteBoardResultComponent implements OnInit {
  public curMember: MemberVo | null;
  //当前页码值
  public page: number = 1;
  //每页显示的数量
  public pageSize: number = 20;
  public pageResult!: EntityPageResult<BoardRecordVo>;
  //当前的URL,用以浏览历史:window.history.pushState
  private url: string = '#';
  private token: string = '123456';
  private ip: string = '127.0.0.1';
  
  constructor(
    private title: Title,
    private location: Location,
    private activatedRoute: ActivatedRoute,
    private boardService:BoardService,
    private memberStorage: MemberStorageService,
    private util: UtilService,
    private btnNaviSharedService: BtnNaviSharedService) {
      this.curMember = this.memberStorage.get();
      this.btnNaviSharedService.active(true);//需要全局导航
      this.activatedRoute.url.pipe(map(s => s.join('/'))).subscribe(res => {
        this.url = '/' + res;
      });
      this.token = this.util.randomAlphaNumeric(8) || '123456';
      this.memberStorage.getIpCliente().subscribe(ipAddr=>this.ip=ipAddr);
  }

  ngOnInit(): void {
    this.title.setTitle('个人中心:版块收藏列表');
    this.page = +(this.activatedRoute.snapshot.queryParamMap.get('p') ?? 1);
    this.pageSize = +(this.activatedRoute.snapshot.queryParamMap.get('s') ?? environment.pageSize);
    this.getDate();
  }

  //加载指定页码的数据
  private getDate(): void {
    this.boardService.getAllFavorite(this.curMember?.id ?? 0, this.page, this.pageSize).subscribe(rs=>this.pageResult = rs);
  }

  //底部的点击加载更多,后期会替换为:自动加载
  public anymore(event: Event): void {
    this.page += 1;
    this.getDate();
    this.location.replaceState(this.url, 'p=' + this.page + '&s=' + this.pageSize);
  }

  //取消收藏
  public cancelFavorite(boardId:number){
    this.boardService.cancelFavorite(boardId, this.curMember?.id??0, this.curMember?.nickname??'guest', this.token, this.ip).subscribe({
      next: response => {
        this.pageResult.result.forEach((data:BoardRecordVo, index:number, rs:BoardRecordVo[])=>{
          if(data.id === boardId){
            rs.splice(index, 1);
          }
        });
        this.util.alertSuccess('版块收藏删除成功');
      },
      error: err => {
        let em: string = '';
        if (err instanceof HttpErrorResponse) {
          if (err.error instanceof ErrorEvent) {
            em = err.error.message;
          } else {
            em = (err.status === 417) ? '操作失败' : err.error;
          }
        } else if (err instanceof Error) {
          em = err.message;
        } else { em = err; }
        this.util.alertError(em);
        console.log('[PersonalFavoriteBoardResult-CTL]cancel favorite error ' + em);
      },
      complete: () => { console.log('[PersonalFavoriteBoardResult-CTL]cancel favorite Completed'); }
    });
  }
}
